<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="RTOS TencentOS-tiny">
    <meta name="description" content="嵌入式 STM32 物联网领域的教程及精彩内容分享">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>05-任务间同步机制的实现，万变不离其宗 | Mculover666</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Mculover666</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-list" style="zoom: 0.6;"></i>
      
      <span>系列教程</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/posts/578764034/">
          
          <span>STM32CubeMX</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>CSDN</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/download" class="waves-effect waves-light">
      
      <i class="fas fa-download" style="zoom: 0.6;"></i>
      
      <span>资源下载</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Mculover666</div>
        <div class="logo-desc">
            
            嵌入式 STM32 物联网领域的教程及精彩内容分享
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-list"></i>
			
			系列教程
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/posts/578764034/ " style="margin-left:75px">
				  
		          <span>STM32CubeMX</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a target="_blank" rel="noopener" href="https://blog.csdn.net/Mculover666" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			CSDN
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/download" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-download"></i>
			
			资源下载
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/9.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">05-任务间同步机制的实现，万变不离其宗</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                                <span class="chip bg-color">RTOS内功修炼记</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/RTOS/" class="post-category">
                                RTOS
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-08-01
                </div>
                

                

                

                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="1-为什么需要任务间同步"><a href="#1-为什么需要任务间同步" class="headerlink" title="1. 为什么需要任务间同步"></a>1. 为什么需要任务间同步</h1><p>实时操作系统中，每个任务都是一个独立的裸机程序，但是这些任务共享同一个CPU、内存空间、外设，操作系统如何解决这个问题呢？</p>
<h2 id="1-1-如何共享同一个CPU"><a href="#1-1-如何共享同一个CPU" class="headerlink" title="1.1. 如何共享同一个CPU"></a>1.1. 如何共享同一个CPU</h2><p>任务是否在使用CPU，体现在该任务是否处于运行状态。</p>
<p>RTOS的内核采用“分时复用CPU”的思想，根据抢占式调度规则、时间片轮转调度规则、中断调度规则来安排系统中的任务分别在不同的时刻运行，这也是我们前面四篇文章中重点讲述的内容。</p>
<p><img src="https://img-blog.csdnimg.cn/2020071109135068.png"></p>
<h2 id="1-2-如何共享同一块内存空间"><a href="#1-2-如何共享同一块内存空间" class="headerlink" title="1.2. 如何共享同一块内存空间"></a>1.2. 如何共享同一块内存空间</h2><p>每个任务的任务栈是独立的，所以每个任务运行的时候，在自己的栈空间内玩的很happy。</p>
<p>如果把整个内存空间看作一栋公寓的话，每个任务会分配有自己的一间房子，自己可以在里面尽情的玩耍，至于你干什么事，其它房间的人根本没法知道，也没必要知道。</p>
<p><img src="https://img-blog.csdnimg.cn/20200711092111766.png"></p>
<p>在一些情况下，可能有一些特殊的内存空间，比如某一个全局变量、或者某一块全局变量数组，每个任务都可以访问并进行操作，堆空间也是如此，每个任务都可以使用malloc和free进行申请和释放。</p>
<p>这些内存空间统一称之为共享内存，它只有一个特性，既是优点也是缺点：<strong>系统中所有的任务都可以随意访问和修改</strong>。</p>
<p>映射到生活中，就类似于厨房、卫生间、浴室、杂物间这种共享房间，如果你在使用的时候别人要强行使用，岂不是乱套了~</p>
<p><img src="https://img-blog.csdnimg.cn/20200711093121347.png"><br>如果加以规则和限制，共享内存的优点就可以被利用起来：</p>
<ul>
<li>优点：因为任务可以随意访问修改，所以可以用作一些<strong>标志位、计数量</strong>，进而引申出信号量这个东东。</li>
<li>缺点：任务可以随意访问修改，所以用作共享数据缓冲区的时候，必须要对前来访问和修改的任务加以控制，保护数据不被随意篡改，进而引申出<strong>互斥锁</strong>这个东东。</li>
</ul>
<p>至于堆空间，可以全部交由系统管理，由<strong>系统提供统一的malloc和free接口</strong>，轻松解决，将在后续文章中重点讲解。</p>
<h2 id="1-3-如何共享同一个外设"><a href="#1-3-如何共享同一个外设" class="headerlink" title="1.3. 如何共享同一个外设"></a>1.3. 如何共享同一个外设</h2><p>因为嵌入式系统的特殊性，系统中还存在大量外设，比如GPIO（包括用GPIO模拟各种软件协议的情况）、串口、I2C接口、SPI接口等。</p>
<p>所有的任务都可以随意的使用这些外设，在task1使用I2C接口操作OLED时，高优先级任务task2因为一定原因突然唤醒，抢占task1，如果task2也通过I2C接口操作OLED，那么在回到task1执行时，肯定无法正常显示内容了（之前与OLED的通信数据全部丢失）。</p>
<p>在操作系统层面，必须要对外设的使用加以权限，即：<strong>当一个任务在使用外设的时候，其它任务无法使用，必须要等该任务使用结束后，其它任务方可正常使用</strong>。</p>
<p>显然，系统管理所有的外设资源就是在开国际玩笑，系统只需提供<strong>互斥锁机制</strong>，对外设加权限的操作留给开发者，简单方便。</p>
<p><img src="https://img-blog.csdnimg.cn/20200711095309532.png#pic_center"></p>
<h1 id="2-pend-post机制"><a href="#2-pend-post机制" class="headerlink" title="2. pend-post机制"></a>2. pend-post机制</h1><p>共享内存（eg. 全局变量）的特性既是优点也是缺点：系统中所有的任务都可以随意访问和修改。</p>
<p><strong>在全局变量的基础上，系统添加一些额外的机制和数据成员，封装为结构体，就是RTOS内核中用于任务间通信的所有东西</strong>，包括：信号量、互斥锁、事件、完成量、计数锁、栅栏，这些东西提供给上层应用的功能都不相同，各有各的特点，供应用在不同的情况下选择使用。</p>
<p>种类很多，但是都具有一个不变的机制：pend-post机制。TencentOS-tiny中的实现在 <code>pend.h</code> 和 <code>pend.c</code> 中。</p>
<h2 id="2-1-等待列表对象"><a href="#2-1-等待列表对象" class="headerlink" title="2.1. 等待列表对象"></a>2.1. 等待列表对象</h2><p>先不管它是干嘛的，知道它长什么样就好，就是一个双向链表节点：</p>
<pre><code class="c">typedef struct pend_object_st &#123;
    k_list_t        list;
&#125; pend_obj_t;
</code></pre>
<h2 id="2-2-pend等待机制实现"><a href="#2-2-pend等待机制实现" class="headerlink" title="2.2. pend等待机制实现"></a>2.2. pend等待机制实现</h2><p>pend的英文释义为“等候判决”，我觉得非常贴切，实现机制也很简单，当任务需要等待这个量时，就挂载到<strong>这个量的等待列表对象上</strong>，源码如下：</p>
<pre><code class="c">__KNL__ void pend_task_block(k_task_t *task, pend_obj_t *object, k_tick_t timeout)
&#123;
    readyqueue_remove(task);

    task-&gt;pend_state = PEND_STATE_NONE;
    pend_list_add(task, object);

    if (timeout != TOS_TIME_FOREVER) &#123;
        tick_list_add(task, timeout);
    &#125;
&#125;
</code></pre>
<blockquote>
<p>如果不是阻塞等待的话，则同时将任务挂载到延时列表上，到点自动唤醒，延时列表在上一篇文章中已经详细讲述。</p>
</blockquote>
<p>① <strong>任务如何挂载到等待列表上？</strong></p>
<p>在任务控制块中有一个数据成员</p>
<pre><code class="c">/**
 * task control block
 */
struct k_task_st &#123;
      //……不相关的都省略了
    k_list_t            pend_list;              /**&lt; when we are ready, our pend_list is in readyqueue; when pend, in a certain pend object&#39;s list. */

    pend_obj_t         *pending_obj;            /**&lt; if we are pending, which pend object&#39;s list we are in? */
    pend_state_t        pend_state;             /**&lt; why we wakeup from a pend */

&#125;;
</code></pre>
<p>其中双向链表节点<code>pend_list</code>在任务就绪的时候挂载到就绪列表上，在任务等待某一个任务同步量时挂载到等待列表上。</p>
<p>② <strong>等待列表上的任务具有有优先级吗？</strong></p>
<p>假设同时有5个任务都在等待同一个互斥锁，一旦互斥锁被释放，按照优先级抢占式调度的规则，肯定是唤醒5个任务里优先级最高的那个任务执行。</p>
<p>TencentOS-tiny中进行了算法优化，在向等待列表上插入任务时，<strong>是按照优先级从高到低排布的</strong>，这样唤醒任务时，永远把最头部的任务拉起就OK，实现源码如下：</p>
<pre><code class="c">__STATIC__ void pend_list_add(k_task_t *task, pend_obj_t *pend_obj)
&#123;
    k_task_t *iter;

    /* keep priority in descending order, the boss(task with highest priority,
       numerically smallest) always comes first
    */
    TOS_LIST_FOR_EACH_ENTRY(iter, k_task_t, pend_list, &amp;pend_obj-&gt;list) &#123;
        if (task-&gt;prio &lt; iter-&gt;prio) &#123;
            break;
        &#125;
    &#125;
    tos_list_add_tail(&amp;task-&gt;pend_list, &amp;iter-&gt;pend_list);

    // remember me, you may use me someday
    task-&gt;pending_obj = pend_obj;
    task_state_set_pend(task);
&#125;
</code></pre>
<blockquote>
<p>知道任务是按照优先级从高到低排列的就行，看不懂源码实现没有影响。</p>
</blockquote>
<h2 id="2-3-post唤醒机制的实现"><a href="#2-3-post唤醒机制的实现" class="headerlink" title="2.3. post唤醒机制的实现"></a>2.3. post唤醒机制的实现</h2><p>当任务同步量被post时，将该任务同步量的等待列表上优先级最高的任务（等待列表上第一个任务）唤醒。</p>
<p>唤醒机制也很简洁，将任务控制块从等待列表上移除，从延时列表中移除，加入到就绪列表中，源码如下：</p>
<pre><code class="c">__KNL__ void pend_task_wakeup(k_task_t *task, pend_state_t state)
&#123;
    if (task_state_is_pending(task)) &#123;
        // mark why we wakeup
        task-&gt;pend_state = state;
        pend_list_remove(task);
    &#125;

    if (task_state_is_sleeping(task)) &#123;
        tick_list_remove(task);
    &#125;

    if (task_state_is_suspended(task)) &#123;
        return;
    &#125;

    readyqueue_add(task);
&#125;
</code></pre>
<p>需要注意，在调用此API的时候，<strong>state参数用来指示任务被唤醒的原因</strong>，供上层应用程序使用，存储在任务控制块的pend_state成员中，有以下任务状态值：</p>
<pre><code class="c">
/**
 * The reason why we wakeup from a pend.
 * when we wakeup, we need to know why.
 */
typedef enum pend_state_en &#123;
    PEND_STATE_NONE,        /**&lt; nothing. */
    PEND_STATE_POST,        /**&lt; someone has post, we get what we want. */
    PEND_STATE_TIMEOUT,     /**&lt; a post has never came until time is out. */
    PEND_STATE_DESTROY,      /**&lt; someone has destroyed what we are pending for. */
    PEND_STATE_OWNER_DIE,   /**&lt; the pend object owner task is destroyed. */
&#125; pend_state_t;
</code></pre>
<h1 id="3-丰富的任务同步量"><a href="#3-丰富的任务同步量" class="headerlink" title="3. 丰富的任务同步量"></a>3. 丰富的任务同步量</h1><p>TencentOS-tiny中提供了非常丰富的任务同步量，适合于各种各样的情况，本文不讲述具体有哪些API以及使用demo，需要阅读的话请移步TencentOS-tiny仓库中的doc目录下的文档：04-TencentOS tiny开发指南。</p>
<p>本文只讲述这些任务同步量在全局变量+pend-post机制的基础上，封装了哪些东西以实现不同的功能。</p>
<h2 id="3-1-信号量"><a href="#3-1-信号量" class="headerlink" title="3.1. 信号量"></a>3.1. 信号量</h2><p>信号量控制块如下：</p>
<pre><code class="c">typedef struct k_sem_st &#123;
#if TOS_CFG_OBJECT_VERIFY_EN &gt; 0u
    knl_obj_t       knl_obj;
#endif

    pend_obj_t      pend_obj;
    k_sem_cnt_t     count;
    k_sem_cnt_t     count_max;
&#125; k_sem_t;
</code></pre>
<p>可以看到其中多了count成员和count_max成员，有什么用呢？</p>
<ul>
<li>① 提供二值信号量功能</li>
</ul>
<p>将count_max设为1，信号量的count值就只有0和1，所以称为二值信号量，通常都是当做一个flag来用。</p>
<ul>
<li>② 提供资源计数功能</li>
</ul>
<p>将count_max设为最大计数值，count就表示当前计数值，可以对资源进行计数，pend成功count会-1，post成功之后count会+1，比如典型的生产者与消费者的例子。</p>
<h2 id="3-2-互斥锁"><a href="#3-2-互斥锁" class="headerlink" title="3.2. 互斥锁"></a>3.2. 互斥锁</h2><p>互斥锁控制块的源码如下：</p>
<pre><code class="c">typedef struct k_mutex_st &#123;
#if TOS_CFG_OBJECT_VERIFY_EN &gt; 0u
    knl_obj_t       knl_obj;
#endif

    pend_obj_t      pend_obj;
    k_nesting_t     pend_nesting;
    k_task_t       *owner;
    k_prio_t        owner_orig_prio;
    k_list_t        owner_anchor;
&#125; k_mutex_t;
</code></pre>
<p>其中pend_nesting成员表示互斥锁是上锁还是解锁状态，同时还表示互斥锁嵌套值，<strong>防止发生互斥锁嵌套</strong>（已经pend成功互斥锁了，还要再次pend），是一个整型：</p>
<pre><code class="c">typedef uint8_t             k_nesting_t;
</code></pre>
<p>owner成员用来记录获取到互斥锁的任务，使得只有获取到互斥锁的那个任务才可以释放互斥锁，其它任务不行。</p>
<p>owner_anchor成员是一个双向链表节点，因为一个可以同时使用多个锁，所以此成员用来<strong>挂载到</strong>任务控制块的 mutex_own_list 列表上。</p>
<p>owner_orig_prio成员记录互斥锁拥有者的任务优先级，用于防止优先级翻转。</p>
<p>任务优先级翻转其实就一句话（虽然有点长）：</p>
<p>任务优先级 A &gt; B &gt; C（最低），当A在挂起等待C释放任务同步量时，结果C由于某种原因被B抢占，导致C释放不了任务同步量，进而导致A得不到任务同步量，造成<strong>低优先级的任务B在跑，而高优先级的A却在等</strong>，在实时系统中这可能会导致非常严重的后果，都是这个B干的好事~</p>
<p>所以<strong>当任务获取到互斥锁之后，会暂时将优先级提到最高，以防止被其它任务打断，释放锁之后恢复原来的优先级</strong>。用户编写的时候也应该尽快的使用完互斥锁并释放。</p>
<h2 id="3-3-事件"><a href="#3-3-事件" class="headerlink" title="3.3. 事件"></a>3.3. 事件</h2><p>事件控制块的源码如下：</p>
<pre><code class="c">typedef struct k_event_st &#123;
#if TOS_CFG_OBJECT_VERIFY_EN &gt; 0u
    knl_obj_t       knl_obj;
#endif

    pend_obj_t      pend_obj;
    k_event_flag_t  flag;
&#125; k_event_t;
</code></pre>
<p>相比之下，只多了一个数据成员flag，用来记录事件标志，表示事件发生与否：</p>
<pre><code class="c">typedef uint32_t            k_event_flag_t;
</code></pre>
<p>一个事件中包含了一个旗标，这个旗标的每一位表示一个“事件”，flag最大可以标志32个事件。</p>
<p>同时，一个任务可以等待一个或者多个“事件”的发生，其他任务在一定的业务条件下可以通过写入特定“事件”唤醒等待此“事件”的任务，实现一种类似信号的编程范式。</p>
<h2 id="3-4-完成量"><a href="#3-4-完成量" class="headerlink" title="3.4. 完成量"></a>3.4. 完成量</h2><p>完成量控制块的源码如下：</p>
<pre><code class="c">typedef struct k_completion_st &#123;
#if TOS_CFG_OBJECT_VERIFY_EN &gt; 0u
    knl_obj_t           knl_obj;
#endif

    pend_obj_t          pend_obj;
    completion_done_t   done;
&#125; k_completion_t;
</code></pre>
<p>其中添加了done成员，用以标志是否完成：</p>
<pre><code class="c">typedef uint16_t    completion_done_t;
</code></pre>
<p>完成量相对来说，是一种简单的任务间通信机制，用以在任务间同步某一事件是否已“完成”的信息。</p>
<h2 id="3-5-计数锁"><a href="#3-5-计数锁" class="headerlink" title="3.5. 计数锁"></a>3.5. 计数锁</h2><p>计数锁控制块的源码如下：</p>
<pre><code class="c">typedef struct k_countdownlatch_st &#123;
#if TOS_CFG_OBJECT_VERIFY_EN &gt; 0u
    knl_obj_t               knl_obj;
#endif

    pend_obj_t              pend_obj;
    k_countdownlatch_cnt_t  count;
&#125; k_countdownlatch_t;
</code></pre>
<p>其中添加了一个count成员，用于存放计数值。</p>
<p>计数锁提供了一种“计数信息”同步的概念，计数锁创建的时候会指定一个计数值，每当有任务执行tos_countdownlatch_post时，该计数锁的计数值减一，直到计数锁的计数值为零时，等待此计数锁的任务才会被唤醒。</p>
<h2 id="3-6-栅栏"><a href="#3-6-栅栏" class="headerlink" title="3.6. 栅栏"></a>3.6. 栅栏</h2><p>栅栏控制块的源码如下：</p>
<pre><code class="c">typedef struct k_barrier_st &#123;
#if TOS_CFG_OBJECT_VERIFY_EN &gt; 0u
    knl_obj_t               knl_obj;
#endif

    pend_obj_t              pend_obj;
    k_barrier_cnt_t         count;
&#125; k_barrier_t;
</code></pre>
<p>其中添加的数据成员count表示计数值。</p>
<p>栅栏提供了一种设置任务阻塞屏障的机制，栅栏创建的时候会指定一个计数值，每当有任务执行tos_barrier_pend时，该计数锁的计数值减一，直到计数锁的计数值为零时，所有阻塞在tos_barrier_pend点上的任务才可以往下运行。</p>
<h1 id="4-总结"><a href="#4-总结" class="headerlink" title="4. 总结"></a>4. 总结</h1><p>按照惯例，对本文的内容作以回顾。</p>
<p>本文主要讲述了RTOS内核中，各种任务同步量的实现多种多样，万变不离其宗，本文中讲述了两个“宗”。</p>
<ul>
<li>① 全局变量具有可以被所有任务访问、修改的特性。</li>
<li>② 每个任务同步量都有<strong>自己的等待列表</strong>，用来挂载当前等待该任务同步量的所有任务，这也是pend-post机制实现的核心，同时需要注意，在只唤醒一个任务时，<strong>唤醒的是等待列表中优先级最高的任务</strong>。</li>
</ul>
<p>基于这两个“宗”，加上不同的数据成员就实现了丰富的任务同步量，其中信号量、互斥锁、事件比较常用，比较如下：</p>
<ul>
<li>信号量：任何任务都可以获取、释放，可以用作<strong>二值</strong>信号标志，也可以用作计数；</li>
<li>互斥锁：任何任务都可以获取，但<strong>只能由拥有者释放</strong>，并且在获取锁之后将拥有者的优先级提至最高，防止优先级翻转，用作外设的保护和共享内存的保护；</li>
<li>事件：任何任务都可以获取、释放，用作标志位，<strong>最大支持32个事件标志</strong>；</li>
</ul>
<p>其余的一些，看你的选择来用了~</p>
<p>最后还有一点，在创建这些任务同步量控制块时，都是<strong>全局变量</strong>哦，这些各种各样的任务同步量只是在普通全局变量的基础上扩展了功能，如果你的场景可以直接用普通全局变量解决，Why not？怎么方便怎么来！</p>
<p>本期文章就到这里啦，如果以后再遇到有国家二级抬杠运动员，非要和你杠，有全局变量不用为什么要用这些任务同步量，请把本文甩给他！</p>
<p>我是喜欢玩板子的小码农Mculover666，下期文章再见~</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Mculover666</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.mculover666.cn/posts/2361665440/">http://www.mculover666.cn/posts/2361665440/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Mculover666</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                                    <span class="chip bg-color">RTOS内功修炼记</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/we-chat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    
    <div class="livere-card card" data-aos="fade-up">
    <!-- 来必力City版安装代码 -->
    <div id="lv-container" class="card-content" data-id="city" data-uid="MTAyMC80Njg0OS8yMzM1MA">
        <script type="text/javascript">
            (function (d, s) {
                let j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') {
                    return;
                }

                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript。</noscript>
    </div>
    <!-- City版安装代码已完成 -->
</div>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/349211769/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/6.jpg" class="responsive-img" alt="06-任务间通信为什么不用全局变量">
                        
                        <span class="card-title">06-任务间通信为什么不用全局变量</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            RTOS内功修炼记
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-08-01
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RTOS/" class="post-category">
                                    RTOS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                        <span class="chip bg-color">RTOS内功修炼记</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/2848765993/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/4.jpg" class="responsive-img" alt="04-小小的时钟节拍，撑起了内核半边天">
                        
                        <span class="card-title">04-小小的时钟节拍，撑起了内核半边天</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            RTOS内功修炼记
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-08-01
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/RTOS/" class="post-category">
                                    RTOS
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/RTOS%E5%86%85%E5%8A%9F%E4%BF%AE%E7%82%BC%E8%AE%B0/">
                        <span class="chip bg-color">RTOS内功修炼记</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2016-2021</span>
            
            <span id="year">2016</span>
            <a href="/about" target="_blank">Mculover666</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">118.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2016";
                    var startMonth = "8";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="https://beian.miit.gov.cn" target="_blank">陇ICP备19002222号</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Mculover666" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:mculover666@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2412828003" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2412828003" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/wang-shi-wei-67-38/activities" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/wang-shi-wei-67-38/activities" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

<script>
    var _hmt = _hmt || [];
    (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?6e1efa0988723a1db6356535db2ae6bd";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
    })();
</script>

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
